package me.qixiaobo.tran.core.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import lombok.extern.slf4j.Slf4j;
import me.qixiaobo.enums.BaseEnum;
import me.qixiaobo.tran.annotation.Translation;
import me.qixiaobo.tran.core.FieldTranStrategy;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * 翻译处理器
 *
 * @Description TranslationHandler
 * @Author guoyb
 * @Date 2024/5/20 16:11
 */
@Slf4j
public class TranslationHandler extends JsonSerializer<Object> implements ContextualSerializer {

    private Translation translation;

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {

        FieldTranStrategy strategy = translation.tranStrategy();
        String key = "";
        String result = "";
        // 如果映射字段不为空 则取映射字段的值
        if (StringUtils.isNotBlank(translation.jsonStr())) {
            JSONObject jsonObject = JSONUtil.parseObj(translation.jsonStr());
            result = strategy.handle(key, jsonObject, null);
        }
        // 如果为 null 直接写出
        if (ObjectUtil.isNull(value)) {
            gen.writeNull();
            return;
        }
        if (ObjectUtil.isNotNull(translation.enumClazz())) {
            Class<? extends BaseEnum> enumClass = translation.enumClazz();
            result = strategy.handle(key, null, enumClass);
        }
        gen.writeObject(result);

        // gen.writeObject(value);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        Translation translation = property.getAnnotation(Translation.class);
        if (Objects.nonNull(translation)) {
            this.translation = translation;
            return this;
        }
        return prov.findValueSerializer(property.getType(), property);
    }
}
